package com.alveole.events;

import java.util.ArrayList;
import java.util.List;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import javax.persistence.Persistence;
import javax.persistence.Query;

import com.alveole.dao.Dao;
import com.alveole.dao.User;
import com.alveole.objects.BrowserSession;

public class BrowserLoginEvent extends BrowserEvent {

	@Override

	public List<ServerEvent> getAnswers_() {
		List <ServerEvent> events = new ArrayList<ServerEvent>();
		
		
		User u=null;
		
		Query q = eventBean.getEntityManager().createQuery("select u from User u Where u.login=:login and u.password=:password");
		q.setParameter("login", parameters.get("login"));
		q.setParameter("password", parameters.get("password"));
		try{
			u = (User) q.getSingleResult();
		}
		catch (NoResultException e)
		{
			events.add(new ErrorEvent("User all login invalid"));
		}
		if (u!=null)
		{
			eventBean.getBrowserSession().setUser(u);
			events.add(new setValueEvent("ALVEOLEauthenticated",true));
			events.add(new setValueEvent("ALVEOLElogin",eventBean.getBrowserSession().getUser().getLogin()));
		}
		return events;
	}

}
